package com.xv.service;

import com.xv.dao.UserMapper;
import com.xv.pojo.Msg;
import com.xv.pojo.User;
import com.xv.pojo.UserExample;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImp implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User findUserByName(String username) {
        UserExample example= new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        try {
            return userMapper.selectByExample(example).get(0);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public User checkLogin(String username, String password) {
        //根据用户名实例化用户对象
        User user = findUserByName(username);
        if (null != user && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public Msg addUser(User user) {
        if (null != findUserByName(user.getUsername())) {
            throw new RuntimeException("用户已存在");
        } else if (user.getPassword().length()>=6) {
            throw new RuntimeException("密码不能小于6位数");
        }
        return userMapper.insert(user);
    }
}
